<template>
	<div class="system-edit-dept-container">
		<el-dialog :title="(formData.id!==0?'修改':'添加')+'订单'" v-model="isShowDialog" width="769px">
			<el-form ref="formRef" :model="formData" :rules="rules" size="default" label-width="90px" :disabled="form_disabled">
				<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
					<el-form-item label="所属店铺" prop="shop_id">
						<el-cascader
							:options="list"
							:props="{ emitPath:false, value: 'id', label: 'name',expandTrigger: 'hover' as const, }"
							placeholder="请选择店铺"
							clearable
							class="w100"
							:show-all-levels="false"
							v-model="formData.shop_id">
						</el-cascader>
					</el-form-item>
				</el-col>
				<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
					<el-form-item label="订单号" prop="order_num">
						<el-input v-model="formData.order_num" placeholder="请输入订单号" clearable disabled></el-input>
					</el-form-item>
				</el-col>
				<el-row :gutter="35">
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="会员">
						  <el-select
							v-model="m_opvalue"
							value-key="id"
							filterable
							remote
							clearable
							reserve-keyword
							placeholder="请输入会员姓名或联系方式"
							:remote-method="memberSearch"
							:loading="m_loading"
							@change="memberChange"
							>
						  <el-option
							v-for="item in m_options"
							:key="item.id"
							:label="item.name"
							:value="item"
						  />
						</el-select>
						&nbsp;&nbsp;&nbsp;
						<el-text v-if="showMemberMoney">余额：{{memberMoney.toFixed(2)}}</el-text>
						</el-form-item>
						
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="名称" prop="name">
							<el-input v-model="formData.name" placeholder="请输入名称" clearable :disabled="m_opvalue?true:false" ></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="联系方式" prop="contact">
							<el-input v-model="formData.contact" placeholder="请输入联系方式" clearable :disabled="m_opvalue?true:false" ></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="地址" prop="address">
							<el-input v-model="formData.address" placeholder="请输入地址" clearable  ></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="开始时间" prop="start_time">
							<el-date-picker v-model="formData.start_time" type="datetime" placeholder="选择开始时间" value-format="YYYY-MM-DD HH:mm:ss"/>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="结束时间" prop="end_time">
							<el-date-picker v-model="formData.end_time" type="datetime" placeholder="选择结束时间" value-format="YYYY-MM-DD HH:mm:ss"/>
						</el-form-item>
					</el-col>
				
						<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
							<el-form-item label="订单金额" prop="money">
								<el-input v-model="formData.money" type="number"  placeholder="金额" clearable></el-input>
							</el-form-item>
						</el-col>
						
		
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						
						<el-form-item label="状态">
							<el-radio-group v-model="formData.status" class="ml-4">
								<el-radio value="1" :label="1">正常</el-radio>
								<el-radio value="2" :label="2">完成</el-radio>
								<el-radio value="0" :label="0">取消</el-radio>
							  </el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						
						<el-form-item label="类型">
							<el-radio-group v-model="formData.type" class="ml-4">
								<el-radio value="1" :label="1">个人</el-radio>
								<el-radio value="2" :label="2">团体</el-radio>
								<el-radio value="3" :label="3">其它</el-radio>
							  </el-radio-group>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否预约单">
							<el-switch v-model="formData.is_appointment" :active-value="1" :inactive-value="0" inline-prompt active-text="是" inactive-text="否"></el-switch>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
						<el-form-item label="是否外出">
							<el-switch v-model="formData.is_out" :active-value="1" :inactive-value="0" inline-prompt active-text="是" inactive-text="否"></el-switch>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="备注">
							<el-input v-model="formData.remark" type="textarea" placeholder="请输入备注" maxlength="150"></el-input>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="客服员工">
							
						  <el-select
							v-model="opvalue"
							value-key="id"
							filterable
							remote
							clearable
							reserve-keyword
							placeholder="请输入员工姓名或联系方式"
							:remote-method="employeeSearch"
							:loading="loading"
							>
						  <el-option
							v-for="item in options"
							:key="item.id"
							:label="item.name"
							:value="item"
						  />
						</el-select>
						</el-form-item>
					</el-col>
					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
						<el-form-item label="指派员工">
							
						  <el-select
							v-model="e_opvalue"
							filterable
							multiple
							remote
							clearable
							placeholder="请输入员工姓名或联系方式"
							:remote-method="employeeSearch2"
							:loading="loading"
							value-key="id"
							>
						  <el-option
							v-for="item in e_options"
							:key="item.id"
							:label="item.name"
							:value="item"
						  />
						</el-select>
						</el-form-item>
					</el-col>
					
				</el-row>
			</el-form>
			<template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
				    
					<el-button type="primary" @click="onSubmit" size="default" :disabled="form_disabled">{{formData.id!==0?'修 改':'添 加'}}</el-button>
	
					<el-text class="mx-1" type="danger" v-if="form_disabled">取消或已完成订单无法修改</el-text>
				</span>
			</template>
		</el-dialog>
	</div>
</template>

<script lang="ts">
import {reactive, toRefs, defineComponent, getCurrentInstance,ref,unref} from 'vue';
import {edit} from "/@/api/zmm/order";
import {getOpQueryList} from "/@/api/zmm/employee";
import {getMemberOpQueryList} from "/@/api/zmm/member";
import {formatDate} from "/@/utils/formatTime";
import { getList} from "/@/api/zmm/shop";
import XLSX from 'xlsx'



import {randomId} from "/@/utils/other";


import {ElMessage} from "element-plus";
import { RefSymbol, trigger } from '@vue/reactivity';

// 定义接口来定义对象的类型
interface TableDataRow {
	name: string;
	contact: string;
	remark: string;
	status: any;
	type: any;
	order_num:string;
}
interface FormState {
  id:number;
  order_num:string;
	name: string;
	contact: string;
	address: string;
	remark: string;
	status: number;
	type: number;
	start_time:string;
	end_time:string;
	is_appointment:number;
	is_out:number;
	member_id:number,
	customer_service_employee_id:number,
	shop_id:number;
	employee_ids:number[];
	money:number;
	
}
interface PageSate {
	isShowDialog: boolean;
	formData: FormState;
	list: Array<TableDataRow>;
  rules: object;
  form_disabled:boolean;
  showMemberMoney:boolean;
	memberMoney:number;
}


export default defineComponent({
	name: 'zmmEditOrder',
	setup(prop,{emit}) {
    const {proxy} = getCurrentInstance() as any;
	const loading = ref(false);
	const options = ref<MOption[]>([]);
	const opvalue = ref<MOption>();
	const m_loading = ref(false);

	type MOption = {
  id: number
  name: string
  contact: string
  money:number;
}

	const m_options = ref<MOption[]>([]);
	const m_opvalue = ref<MOption>();

	const e_options = ref<MOption[]>([]);
	const e_opvalue = ref<MOption[]>([]);


		const checkEndTime = (rule: any, value: any, callback: any)=>{
			if(!value) return callback()
			return value > state.formData.start_time ? callback() : callback(new Error('结束时间必须大于开始时间'))
		};

    const formRef = ref<HTMLElement | null>(null);
		const state = reactive<PageSate>({
			isShowDialog: false,
			showMemberMoney:false,
			memberMoney:0.0,
			formData: {
        		id:0,
				name: '', // 部门名称
				contact:'',
				remark:'',
				status: 1,
				type: 1,
				address:'店内',
				
				order_num:"O"+randomId(),
				start_time:formatDate(new Date, "YYYY-mm-dd HH:MM:SS"),
				end_time:'',
				is_appointment:0,
				is_out:0,
				member_id:0,
				customer_service_employee_id:0,
				shop_id:0,
				employee_ids:[],
				money:0,
			},
			form_disabled:false,
			list: [], // 数据
      rules: {
		shop_id:[
			{required: true, message: "请选择店铺", trigger: "blur"}, {validator:(rule: any, value: any, callback: any)=>{ console.log(value); return value > 0 ?callback():callback(new Error('请选择店铺'));}, trigger: "blur"}
	  ],
        name:[
          {required: true, message: "名称不能为空", trigger: "blur"},
	  ],contact:[
		{required: true, message: "联系方式不能为空", trigger: "blur"},
	  ],start_time:[
		{required: true, message: "开始时间不能为空", trigger: "blur"},
	  ],end_time:[{validator:checkEndTime, trigger: 'change'}],
	  money:[{validator:(rule: any, value: any, callback: any)=>{ 

		if(value <= 0)  return callback(new Error('订单金额必须大于0'));
		if(state.showMemberMoney && state.memberMoney < value ) return callback(new Error('会员账户余额不足'));

		return callback();

	}, trigger: "blur"}]
      }
		});

		
		
		// 打开弹窗
		const openDialog = (row?: FormState|number) => {
      resetForm()
      getList().then((res:any)=>{
		// const list = { id: 0, name: '主店铺', children: [] };
		let list = proxy.handleTree(res.data.zmm_shop_list??[], "id","up_id");
		console.log(list)
          state.list=list;//new Array(list) as any;
      });
		
      if(row && typeof row === "object"){
        state.formData = row;
		
		options.value = row.customer_service_employee?[row.customer_service_employee]:[]
		opvalue.value = row.customer_service_employee?row.customer_service_employee:{};
		
		
		m_options.value = row.member_info?[row.member_info]:[]
		m_opvalue.value = row.member_info?row.member_info:{};
		e_options.value = row.employee_infos?row.employee_infos:{}
		e_opvalue.value = row.employee_infos?row.employee_infos:{};
		if(row.status == 2 || row.status == 0) {state.form_disabled = true;}
		else {
			
			if(row.member_info ){
				state.memberMoney = parseFloat(row.member_info.money)
				state.showMemberMoney = true
			}
		}
      }
			state.isShowDialog = true;
		};
		// 关闭弹窗
		const closeDialog = () => {
			state.isShowDialog = false;
		};
		// 取消
		const onCancel = () => {
			closeDialog();
		};
		// 新增
		const onSubmit = () => {
      const formWrap = unref(formRef) as any;
      if (!formWrap) return;
      formWrap.validate((valid: boolean) => {
        if (valid) {
        //   if(state.ruleForm.deptId===0){
        //     //添加
        //     addDept(state.ruleForm).then(()=>{
        //       ElMessage.success('角色添加成功');
        //       closeDialog(); // 关闭弹窗
        //       emit('deptList')
        //     });
        //   }else{
			state.formData.member_id = m_opvalue.value?m_opvalue.value.id:0
			state.formData.customer_service_employee_id = opvalue.value>0?opvalue.value.id:0
			// console.log()
			// state.formData.employee_ids = e_opvalue.value?e_opvalue.value.map((v)=>{return v.id;}).join(","):""
			state.formData.employee_ids = e_opvalue.value && e_opvalue.value.length > 0?e_opvalue.value.map((v)=>{return v.id;}):[]


			// state.formData.status = parseInt(state.formData.status.value)
			// state.formData.type = parseInt(state.formData.type.value)
			// console.log(state.formData)
			// return
            //修改
            edit(state.formData).then(()=>{
              ElMessage.success('修改成功');
              closeDialog(); // 关闭弹窗
              emit('list')
            });
        //   }
        }
      });
		};
		const employeeSearch = (query: string)=>{
			if(query){
				loading.value = true
				getOpQueryList({
					op_query:query,
				}).then((res)=>{
					loading.value = false
					options.value = res.data.list
				})
			}
		};
		const employeeSearch2 = (query: string)=>{
			if(query){
				loading.value = true
				getOpQueryList({
					op_query:query,
				}).then((res)=>{
					loading.value = false
					e_options.value = res.data.list
				})
			}
		};
		const memberSearch = (query: string)=>{
			if(query){
				m_loading.value = true
				getMemberOpQueryList({
					op_query:query,
				}).then((res)=>{
					m_loading.value = false
					m_options.value = res.data.list
					console.log(m_options.value)
				})
			}
		};
		const memberChange = (value:any)=>{
			if(value){
				state.memberMoney = parseFloat(value.money)
				state.showMemberMoney = true
			}else{
				state.memberMoney = 0.0
				state.showMemberMoney = false
			}
			state.formData.name = value.name
			state.formData.contact = value.contact
		};
    const resetForm = ()=>{
      state.formData = {
        id:0,
		order_num:"O"+randomId(),
        name: '', 
				contact:'',
				remark:'',
				status:1,
				address:'店内',
				start_time:formatDate(new Date, "YYYY-mm-dd HH:MM:SS"),
				end_time:'',
				type: 1,
				is_appointment:0,
				is_out:0,
				member_id:0,
				customer_service_employee_id:0,
				shop_id:0,
				employee_ids:[],
				money:0,
      },
	  state.form_disabled = false;
	  options.value=[]
	  opvalue.value = undefined
	  m_options.value = []
	  m_opvalue.value = undefined
	  e_options.value = []
	  e_opvalue.value = []
	  state.showMemberMoney=false
	  state.memberMoney=0.0
    };
	let radio = ref('3');
		return {
			openDialog,
			closeDialog,
			onCancel,
			onSubmit,
			employeeSearch,
			employeeSearch2,
			memberSearch,
			memberChange,
      formRef,
	  loading,
	  options,
	  opvalue,
	  m_loading,
	  m_options,
	  m_opvalue,
	  e_options,
	  e_opvalue,
			...toRefs(state),
		};
	},
});
</script>
